<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="false"
    :show-close="true"
    :close-on-click-modal="false"
    class="medium-common-dialog-size risk-dialog"
  >
    <Title :title="!kindId?'添加预警通知':'编辑预警通知'" font-size="16px" style="margin-bottom:16px;"/>
    <div :style="{maxHeight: maxHeight}" class="body-form">
      <el-form
        ref="riskForm"
        :rules="rules"
        :model="queryData"
        :label-position="showMobilePage?'left':'right'"
        :label-width="showMobilePage?'100px':'120px'"
        class="notice-form">
        <el-form-item label="预警类型" prop="module">
          <el-select
            v-model="queryData.module"
            size="small"
            placeholder="请选择预警类型"
            @change="changeModule($event)">
            <el-option
              v-for="item in taskModulesOptions"
              :key="item.id"
              :label="item.value"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item :required="true" label="通知条件" class="condition-label">
          <el-tooltip placement="top">
            <div slot="content">以下条件关系为且</div>
            <tipIcon is-diy class="ml5 tip"/>
          </el-tooltip>
          <conditionGroup ref="conditionGroup" :condition="queryData.condition" :options="options" :level-list="clientLevel" :mobile="showMobilePage"/>
        </el-form-item>
        <el-form-item v-if="queryData.module === 2" label="通知角色" prop="role">
          <el-checkbox-group v-model="queryData.role">
            <el-checkbox v-for="(ele, ind) in roleList" :key="ind" :label="ele.value">{{ ele.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="通知周期" prop="cycle">
          <selectWithoutHttp
            v-model="queryData.cycle"
            :list-data="cycleOptions"
            class="width240"
            placeholder="请选择通知的周期"
            @change="cycleChange"
          />
        </el-form-item>
        <el-form-item v-if="queryData.cycle === 2 || queryData.cycle === 3" :label="cycleDayLabel" prop="cycleDay">
          <selectWithoutHttp
            v-model="queryData.cycleDay"
            :list-data="cycleDayOptions"
            :placeholder="cycleDayPlaceholder"
            clearable
          />
        </el-form-item>
        <el-form-item v-if="queryData.cycle !== 0" :key="queryData.date" label="通知时间" prop="date">
          <el-time-select
            v-model="queryData.date"
            :picker-options="{ start: '00:00', step: '00:30', end: '23:30' }"
            value-format="timestamp"
            size="small"
            placeholder="请选择通知时间"
            @visible-change="$forceUpdate()"/>
        </el-form-item>
        <el-form-item label="通知生效范围" class="indentation-form-item">
          <span class="tip">{{ formatTip(queryData.module) }}</span>
          <el-cascader
            v-select-scroll
            v-model="queryData.department"
            :show-all-levels="false"
            :options="deptTreeList"
            :props="{
              emitPath:false,
              value: 'id',
              label: 'name',
              checkStrictly: true,
              multiple: true,
            }"
            filterable
            class="multiple-select-scroll mb10"
            placeholder="请选择生效部门"
            size="small"
            collapse-tags
            clearable>
            <template slot-scope="{ data }">
              <ToolTip v-if="data.name.length > 14" :content="data.name"/>
              <span v-else>{{ data.name }}</span>
            </template>
          </el-cascader>
          <el-select
            v-model="queryData.position"
            :style="'display:block;'"
            class="mb10 width240"
            placeholder="请选择生效职位"
            multiple
            collapse-tags
            filterable
            size="small">
            <el-option
              v-for="(item, index) in postObj.items"
              :key="index"
              :label="item"
              :value="item" />
          </el-select>
          <selectWithUserLoad
            v-model="queryData.effectUser"
            :default-list="queryData.effectUser || []"
            :value-type="'object'"
            key-name="id"
            style="width:240px;"
            label-name="userName"
            placeholder="请选择生效人员"
            multiple
            filterable
            collapse-tags
            clearable
            class="mb10"
          />
          <el-checkbox-group v-model="queryData.notifyType">
            <el-checkbox v-for="(ele, ind) in notifyList" :key="ind" :label="ele.value">
              <div class="flex-center">{{ ele.label }}<tip-icon v-if="ele.value === 2" class="ml4" content="该选项不受限于“通知生效范围”中的设置"/></div>
            </el-checkbox>
          </el-checkbox-group>
          <selectWithUserLoad
            v-if="queryData.notifyType.includes(2)"
            v-model="queryData.specUser"
            :default-list="queryData.specUser || []"
            :value-type="'object'"
            key-name="id"
            style="width:240px;"
            label-name="userName"
            placeholder="请选择指定通知人员"
            multiple
            filterable
            collapse-tags
            clearable
          />
        </el-form-item>
        <el-form-item label="通知内容" prop="notifyContent" class="notifyContent">
          <div v-if="showFillTempBtn" class="flex-center fill-btn">
            <div class="mr5" @click="fillTemp">填充模版</div>
            <tipIcon :content="`模版内容：${customerTemplate}`"/>
          </div>
          <el-input v-model="queryData.notifyContent" :maxlength="100" resize="none" type="textarea" size="small" placeholder="请输入通知内容" />
        </el-form-item>
      </el-form>
    </div>
    <div class="btn-container">
      <el-button :loading="loading" type="primary" size="small" @click="handleOk">确定</el-button>
      <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import Title from '@/components/Title';
import { getDepartmentAll, addRiskNotice, editRiskNotice } from '@/api/config';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import conditionGroup from './conditionGroup.vue';
import { format } from '@/filters/date';
import { allDeptlist } from '@/api/select';
import { getAllPost } from '@/api/user';
import { getLevelList } from '@/api/customer';
import { handelDepartmentData } from '@/utils';
import { moduleOptions, roleList, list, taskModulesOptions, cycleOptions } from './data';
import ElMessage from '@/utils/message';
import { mapState } from 'vuex';

export default {
  components: { Title, selectWithoutHttp, selectWithUserLoad, conditionGroup },
  data() {
    return {
      options: [],
      dialogVisible: false,
      kindId: null,
      queryData: {
        module: [],
        effectUser: [],
        specUser: [],
        department: [],
        cycle: '',
        cycleDay: '',
        date: '',
        notifyType: [],
        role: [],
        condition: [{ field: '', condition: '', value_type: '', value: '', valueTypeList: [] }]
      },
      rules: {
        module: [{ required: true, trigger: 'change', message: '请选择预警类型' }],
        cycle: [{ required: true, trigger: 'change', message: '请选择通知周期' }],
        cycleDay: [{ required: true, trigger: 'change', message: '请选择通知日期' }],
        date: [{ required: true, trigger: 'change', message: '请选择通知时间' }],
        notifyContent: [{ required: true, trigger: 'change', message: '请输入通知内容' }]
      },
      loading: false,
      deptTreeList: [],
      isEdit: false,
      allDeptList: [],
      taskModulesOptions,
      cycleOptions,
      // list,
      roleList,
      postObj: {
        page: 1,
        perPage: 300,
        items: [],
        total: 0
      },
      postLoading: false,
      clientLevel: [],
      maxHeight: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    cycleDayLabel() {
      const cycle = this.queryData.cycle;
      let label = '';
      switch (cycle) {
        case 2: label = '选择星期'; break;
        case 3: label = '选择日期'; break;
      }
      return label;
    },
    cycleDayPlaceholder() {
      const cycle = this.queryData.cycle;
      let label = '请选择';
      switch (cycle) {
        case 2: label = '请选择星期几'; break;
        case 3: label = '请选择每月几号'; break;
      }
      return label;
    },
    cycleDayOptions() {
      const cycle = this.queryData.cycle;
      let options = [];
      if (cycle === 2) {
        options = [
          { id: 1, value: '星期一' }, { id: 2, value: '星期二' },
          { id: 3, value: '星期三' }, { id: 4, value: '星期四' },
          { id: 5, value: '星期五' }, { id: 6, value: '星期六' },
          { id: 7, value: '星期日' }
        ];
      } else if (cycle === 3) {
        for (let i = 1; i <= 31; i++) {
          options.push({ id: i, value: `每月${i}号` });
        }
      }
      return options;
    },
    notifyList() {
      const temp = JSON.parse(JSON.stringify(list));
      return temp.filter(el => !el.module || el.module.includes(this.queryData.module)) || [];
    },
    customerTemplate() {
      if (!this.showFillTempBtn) return '';
      const fields = ['周期内新增欠款金额', '周期内新增逾期金额'];
      const fitCondition = this.queryData.condition.filter(i => fields.includes(i.field));
      let content = '';
      fitCondition.forEach((j, index) => {
        const unit = j.value_type === '欠款额度' ? '%' : '元';
        const prefix = j.value_type === '欠款额度' ? '欠款额度的' : '';
        const value = j.value ? `${prefix}${j.value}${unit}` : `{{${j.value_type === '欠款额度' ? '欠款额度' : '数值'}${unit}}}`;
        content += `新增${j.value_type ? j.field === '周期内新增欠款金额' ? '欠款金额' : '逾期金额' : '{{欠款金额/逾期金额}}'}已${this.conditionMap(j.condition) || '{{等于/大于/小于}}'}${value}${index === fitCondition.length - 1 ? '' : '且'}`;
      });
      const temp = `${this.cycleMap(this.queryData.cycle) || '{{本日/本周/本月}}'}${content || '新增{{欠款金额/逾期金额}}已{{等于/大于/小于}}{{12345元}}'}，请及时催款、核销或申请提升额度`;
      return temp;
    },
    showFillTempBtn() {
      const fields = ['周期内新增欠款金额', '周期内新增逾期金额'];
      return this.queryData.condition.some(el => fields.includes(el.field));
    }
  },
  created() {
    this.queryDeptTreeList();
    this.getAllDeptList();
    this.getPostData();
    this.getCustomeLevelData();
  },
  methods: {
    formatTip(val) {
      return {
        0: '(当客户所属销售在以下范围内进行通知)',
        1: '(当用户在以下范围内进行通知)',
        2: '(当所勾选通知角色在以下范围内进行通知)'
      }[val];
    },
    getCustomeLevelData() {
      getLevelList().then(res => {
        const { data } = res;
        this.clientLevel = data || [];
      }).catch(e => {
        console.log(e);
      });
    },
    getPostData() {
      this.postLoading = true;
      getAllPost(this.postObj).then(res => {
        this.postLoading = false;
        this.postObj.items = res.data.items;
      }).catch(_ => {
        this.postLoading = false;
      });
    },
    changeModule(val) {
      this.options = moduleOptions[val];
      this.$refs.conditionGroup.initData();
    },
    openDialog(item = null) {
      this.isEdit = false;
      const clientHeight = window.innerHeight;
      this.maxHeight = ((clientHeight * 2) / 3) + 'px';
      if (item) {
        this.isEdit = true;
        const data = JSON.parse(JSON.stringify(item));
        // 接收对象根据type不同，选择用户或者部门
        data.cycle = Number(data.cycle);
        if (data.cycle === 0 || data.cycle === 1) data.cycleDay = 0;
        data.condition.forEach(item => {
          const temp = moduleOptions[data.module].find(i => i.value === item.field);
          item.valueTypeList = temp || {};
          if (!item.value) { // 赋值预计到款金额
            item.value = item.value_type;
          }
          delete item.valueName;
        });
        data.effectUser.forEach(item => {
          item.userName = item.name;
        });
        data.specUser.forEach(item => {
          item.userName = item.name;
        });
        this.options = moduleOptions[data.module];
        this.queryData = data;
        this.kindId = data.id;
        this.$nextTick(() => {
          this.$refs.conditionGroup.emitEditEvent();
        });
      }
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs['riskForm'].clearValidate();
      });
    },
    handleClose() {
      this.$refs['riskForm'].resetFields();
      this.queryData = {
        module: [],
        effectUser: [],
        specUser: [],
        department: [],
        cycle: '',
        cycleDay: '',
        date: '',
        notifyType: [],
        role: [],
        condition: [{ field: '', condition: '', value_type: '', value: '', valueTypeList: {}}]
      };
      this.dialogVisible = false;
    },
    // 校验条件是否填写完整
    validateCondition() {
      const temp = this.queryData.condition.every(item => {
        const values = Object.values(item);
        // 每个都不为空，填了，false则为没填
        return values.every(i => i !== '');
      });
      return temp;
    },
    handleOk() {
      if (!this.validateCondition()) {
        ElMessage.warning('通知条件未填写完整！');
        return;
      }
      this.$refs.riskForm.validate(vaild => {
        if (vaild) {
          const params = JSON.parse(JSON.stringify(this.queryData));
          // 处理条件中的unit
          params.condition.forEach(item => {
            if (item.unit === '%') {
              item.value = Number(item.value) / 100;
            }
            // 给客户等级,核销金额赋值value
            if (!item.value_type) {
              item.value_type = typeof item.value === 'number' ? item.field : item.value;
              item.value = typeof item.value === 'number' ? item.value : null;
            }
            delete item.valueTypeList;
            delete item.unit;
          });
          if (params.cycle === 2 || params.cycle === 3) {
            // params.noticeTime = `${params.cycle}/${params.cycleDay}/${format(params.date, 'HH:mm:ss')}`;
            params.noticeTime = `${params.cycle}/${params.cycleDay}/${params.date}`;
          } else if (params.cycle === 1) {
            // params.noticeTime = `${params.cycle}/${format(params.date, 'YYYY-MM-DD')}/${format(params.date, 'HH:mm:ss')}`;
            params.noticeTime = `${params.cycle}/${format(new Date().getTime(), 'YYYY-MM-DD')}/${params.date}`;
          } else {
            params.noticeTime = '';
          }
          params.effectUser = params.effectUser.map(item => { return item.id; });
          params.specUser = params.specUser.map(item => { return item.id; });
          if (this.isEdit) {
            this.toEdit(params);
          } else {
            this.toAdd(params);
          }
        } else {
          return false;
        }
      });
    },
    toAdd(params) {
      this.loading = true;
      addRiskNotice(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$emit('update');
          this.$message.success('添加成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.loading = false;
        this.dialogVisible = false;
        console.error(err);
      });
    },
    toEdit(params) {
      this.loading = true;
      params.id = this.kindId;
      editRiskNotice(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          this.$emit('update');
          this.$message.success('编辑成功');
          this.handleClose();
        } else {
          this.$message.error(res.message);
        }
      }).catch(err => {
        this.loading = false;
        this.dialogVisible = false;
        console.error(err);
      });
    },
    cycleChange() {
      this.queryData.cycleDay = '';
    },
    parseTime(time) {
      // 时分秒转成毫秒的时间戳
      return Date.parse('2021-01-01 ' + time);
    },
    getAllDeptList() {
      allDeptlist().then(res => {
        handelDepartmentData(res.data, true);
        this.allDeptList = res.data;
      });
    },
    queryDeptTreeList(sort = false) {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    fillTemp() {
      this.$set(this.queryData, 'notifyContent', this.customerTemplate);
    },
    conditionMap(condition) {
      return {
        '>': '大于',
        '=': '等于',
        '<': '小于',
        '>=': '大于等于',
        '<=': '小于等于'
      }[condition];
    },
    cycleMap(type) {
      return {
        1: '本日',
        2: '本周',
        3: '本月'
      }[type];
    }
  }
};
</script>
<style lang="scss" scoped>
.risk-dialog {
  ::v-deep {
    .el-dialog {
      width: 350px;
      border-radius: 5px;
    }
    .el-dialog__body {
      padding: 20px;
    }
    .el-dialog__header {
      padding: 0;
    }
  }
}
.body-form {
  @include scrollBar($width: 6px)
}
.notice-form {
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
    .el-checkbox {
      margin-right: 18px;
    }
    .el-select__tags{
      margin-top: 0px;
    }
    .el-tag.el-tag--info {
      color: #406eff;
      background: #eff3fb;
      display: flex;
      align-items: center;
      .el-tag__close {
        right: 0;
        margin: 0 0 0 3px;
      }
    }
    .indentation-form-item {
      position: relative;
      margin-bottom: 16px;
      .el-checkbox__label {
        padding-left: 4px !important;
      }
      label {
        line-height: 1.2 !important;
      }
      .tip {
        position: absolute;
        left: -98px;
        top: 16px;
        width: 95px;
        color: #999;
        font-size: 12px;
        line-height: 1.2;
      }
    }
  }
}

.condition-label {
  position: relative;
  margin-bottom: 16px;
  & ::v-deep {
    .el-form-item__label {
      padding-right: 30px !important;
    }
  }
  .tip {
    position: absolute;
    left: -30px;
    top: 8px;
  }
}
.mb10 {
  margin-bottom: 10px;
}
.btn-container {
  display: flex;
  justify-content: center;
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-select {
      width: 240px;
    }
    .el-input__inner {
      width: 240px;
    }
  }
}
.notifyContent {
  position: relative;
  padding-right: 32px;
  .fill-btn {
    position: absolute;
    top: -30px;
    right: 2px;
    color: #406eff;
    cursor: pointer;
  }
}
</style>
